package com.jiantong.standalone.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by ThinkPad on 2017/7/10.
 */
@WebFilter(urlPatterns = "/*", filterName = "loginFilter")
public class loginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        Cookie[] cookies = null;
        cookies = httpRequest.getCookies();
        String uri = httpRequest.getRequestURI();
        if ("/login".equals(uri)||uri.contains("/webjars")||"/doLogin".equals(uri)) {
            chain.doFilter(httpRequest, httpResponse);
        } else {
            if (cookies != null) {
                Boolean login = false;
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("djtid")) {
                        login =true;
                    }
                }
                if(!login){
                    ((HttpServletResponse) response).sendRedirect("/login");
                }else{
                    chain.doFilter(httpRequest, httpResponse);
                }
            }else{
                ((HttpServletResponse) response).sendRedirect("/login");
            }

        }
    }

    @Override
    public void destroy() {

    }
}
